package cn.crism.commons;


import cn.crism.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @CreateDate: 2018/12/13 2:35 PM
 * @Description:
 * @Author: Crism
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    /* 请求实现前 */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request ---> url:{}, params:{}",url, JsonMapper.object2String(parameterMap));
        return true;
    }
    /* 请求正常实现后 */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request finished ---> url:{}, params:{}",url, JsonMapper.object2String(parameterMap));
    }

    /* 请求实现后不管是否正常处理 */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("exception finished ---> url:{}, params:{}",url, JsonMapper.object2String(parameterMap));

    }
}
